package com.credithc.signature.manager.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.signature.common.constant.CacheConstant;
import com.credithc.signature.common.constant.ManagerConstant;
import com.credithc.signature.common.constant.SealConstant;
import com.credithc.signature.common.mapper.ChannelMapper;
import com.credithc.signature.common.mapper.TemplateExtMapper;
import com.credithc.signature.common.mapper.TemplateMapper;
import com.credithc.signature.common.po.Channel;
import com.credithc.signature.common.po.Template;
import com.credithc.signature.common.po.TemplateExt;
import com.credithc.signature.common.po.TemplateHistory;
import com.credithc.signature.common.ro.manager.ApprovalRo;
import com.credithc.signature.common.service.ChannelService;
import com.credithc.signature.common.service.DictionaryService;
import com.credithc.signature.common.service.TemplateService;
import com.credithc.signature.common.utils.CacheUtil;
import com.credithc.signature.common.utils.GeneralUtil;
import com.credithc.signature.common.utils.UUIDUtil;
import com.credithc.signature.manager.client.ApprovalClient;
import com.credithc.signature.manager.client.AuthClient;
import com.credithc.signature.manager.mapper.TemplateHistoryMMapper;
import com.credithc.signature.manager.mapper.TemplateMMapper;
import com.credithc.signature.manager.ro.ProductRo;
import com.credithc.signature.manager.ro.TemplateRo;
import com.credithc.signature.manager.ro.TokenRo;
import com.credithc.signature.manager.utils.FileUploadUtil;
import com.credithc.signature.manager.vo.CompanyProductVo;
import com.credithc.signature.manager.vo.TemplateVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TemplateMService extends TemplateService {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private ApprovalClient approvalClient;

    @Autowired
    private MessageFactory messageFactory;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private TemplateMMapper templateMMapper;

    @Autowired
    private TemplateHistoryMMapper templateHistoryMMapper;


    public PageInfo<TemplateVo> search(TemplateRo templateRo) {
        Integer companyId = templateRo.getCompanyId();
        String code = templateRo.getCode();
        Integer userId = templateRo.getUserId();
        CompanyProductVo productMap = companyService.getProductMap(code, companyId, userId);
        List<String> channelIds = productMap.getChannelIds();
        Map<String, ProductRo> proMap = productMap.getProMap();
        if (companyId != null || userId != null) {
            if (channelIds.size() < 1) {
                return new PageInfo<>(new ArrayList<>(), 0, 0, 0);
            } else {
                templateRo.setProductIds(channelIds);
            }
        }

        List<TemplateVo> templates = null;
        int count = 0;
        try {
            templates = templateMMapper.selectByRo(templateRo, new RowBounds((templateRo.getPageNo() - 1) * templateRo.getPageSize(), templateRo.getPageSize()));
            count = templateMMapper.selectCountByRo(templateRo);
        } catch (Exception e) {
            log.error("模板查询方法[search-1]发生异常", e);
        }

        bulidTemplateVos(proMap, templates);
        List<Integer> approvalIds = new ArrayList<>();
        Map<Integer, TemplateVo> map = new HashMap<>(16);
        for (TemplateVo tv : templates) {
            approvalIds.add(tv.getApprovalId());
            map.put(tv.getApprovalId(), tv);
        }

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        Message userByToken = authClient.getUserByToken(token);
        Map user = null;
        if (userByToken.getCode() == 0) {
            user = (HashMap) userByToken.getData();
        }

        try {
            Message approverUsers = approvalClient.getApproverUser(approvalIds, token);
            if (approverUsers.getCode() == 0) {
                List<Map> auvs = (List<Map>) approverUsers.getData();
                if (user != null) {
                    for (Map auv : auvs) {
                        TemplateVo templateVo = map.get(auv.get("id"));
                        if ((user.get("ehrId")).equals(auv.get("approverNowId"))) {
                            templateVo.setApprovalUser(true);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("模板查询方法[search-2]发生异常", e);
        }
        return new PageInfo<>(templates, count, templateRo.getPageNo(), templateRo.getPageSize());
    }

    private void bulidTemplateVos(Map<String, ProductRo> proMap, List<TemplateVo> templates) {
        for (TemplateVo t : templates) {
            ProductRo productRo = proMap.get(t.getChannelNo());
            if (productRo != null) {
                t.setTenant(productRo.getCompanyName());
                t.setChannelName(productRo.getProductName());
                t.setSealPerson(productRo.getUserName());
            }
            //创建人、修改人+ehrId
            t.setCreateUser(t.getCreateUser() + "/" + t.getCreateId());
            if (StringUtils.isNotBlank(t.getUpdateUser())) {
                t.setUpdateUser(t.getUpdateUser() + "/" + t.getUpdateId());
            }
            try {
                t.setSealType(dictionaryService.selectOneByTypeAndCode(ManagerConstant.SEAL_TYPE, t.getSealType()));
            } catch (Exception e) {
            }
            try {
                t.setTemplateStatus(dictionaryService.selectOneByTypeAndCode(ManagerConstant.COMMON_STATUS, t.getTemplateStatus()));
            } catch (Exception e) {
            }
            try {
                t.setAuditStatus(dictionaryService.selectOneByTypeAndCode(ManagerConstant.AUDIT_STATUS, t.getAuditStatus()));
            } catch (Exception e) {
            }
            try {
                t.setVip(dictionaryService.selectOneByTypeAndCode(ManagerConstant.IS_VIP, t.getVip()));
            } catch (Exception e) {
            }
        }
    }


    /**
     * 更新模板状态
     *
     * @param id
     * @param status
     */
    public void updateStatus(Long id, Integer status) {
        Example example = new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        Template template = new Template();
        template.setId(id);
        template.setTemplateStatus(status);
        try {
            templateMMapper.updateByExampleSelective(template, example);
        } catch (Exception e) {
            log.error("更新模板状态发生异常", e);
        }
    }

    public void updateVip(Long id, Integer vip) {
        Example example = new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        Template template = new Template();
        template.setId(id);
        template.setVip(vip);
        try {
            templateMMapper.updateByExampleSelective(template, example);
        } catch (Exception e) {
            log.error("更新模板vip发生异常", e);
        }
    }

    public PageInfo<TemplateVo> searchHistory(TemplateRo templateRo) {
        Integer companyId = templateRo.getCompanyId();
        String code = templateRo.getCode();
        Integer userId = templateRo.getUserId();
        CompanyProductVo productMap = companyService.getProductMap(code, companyId, userId);
        List<String> channelIds = productMap.getChannelIds();
        Map<String, ProductRo> proMap = productMap.getProMap();
        if (companyId != null || userId != null) {
            if (channelIds.size() < 1) {
                return new PageInfo<>(new ArrayList<>(), 0, 0, 0);
            } else {
                templateRo.setProductIds(channelIds);
            }
        }

        List<TemplateVo> templates = new ArrayList<>();
        int count = 0;
        try {
            templates = templateHistoryMMapper.selectByRo(templateRo, new RowBounds((templateRo.getPageNo() - 1) * templateRo.getPageSize(), templateRo.getPageSize()));
            count = templateHistoryMMapper.selectCountByRo(templateRo);
        } catch (Exception e) {
            log.error("查询历史模板[searchHistory]方法发生异常", e);
        }

        if (!templates.isEmpty()) {
            bulidHistroyTemplateVos(proMap, templates);
        }

        return new PageInfo<>(templates, count, templateRo.getPageNo(), templateRo.getPageSize());
    }

    private void bulidHistroyTemplateVos(Map<String, ProductRo> proMap, List<TemplateVo> histories) {
        for (TemplateVo t : histories) {
            ProductRo productRo = proMap.get(t.getChannelNo());
            if (productRo != null) {
                t.setTenant(productRo.getCompanyName());
                t.setChannelName(productRo.getProductName());
                t.setSealPerson(productRo.getUserName());
            }
            //创建人、修改人+ehrId
            t.setCreateUser(t.getCreateUser() + "/" + t.getCreateId());
            if (StringUtils.isNotBlank(t.getUpdateUser())) {
                t.setUpdateUser(t.getUpdateUser() + "/" + t.getUpdateId());
            }
            try {
                t.setSealType(dictionaryService.selectOneByTypeAndCode(ManagerConstant.SEAL_TYPE, t.getSealType() + ""));
            } catch (Exception e) {
            }
        }
    }

    public Integer getCount() {
        Example example = new Example(Template.class);
        int i = 0;
        try {
            i = templateMMapper.selectCountByExample(example);
        } catch (Exception e) {
            log.error("数据库错误 " + e.getMessage());
        }
        return i;
    }

    public Integer getHistoryCount() {
        Example example = new Example(TemplateHistory.class);
        int i = 0;
        try {
            i = templateHistoryMMapper.selectCountByExample(example);
        } catch (Exception e) {
            log.error("数据库错误 " + e.getMessage());
        }
        return i;
    }

    @Autowired
    private TemplateExtMapper templateExtMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public Integer uploadext(MultipartFile file) {
        //文件大小限制
        if (file.getSize() > 100 * 1024) {
            log.error("文件太大 ，文件大小为{}", file.getSize());
            return -1;
        }
        TemplateExt templateExt = new TemplateExt();
        String upload = null;
        try {
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String prefix = ".html";
            File path = new File("/data/files/");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file1 = new File(path + File.separator + UUIDUtil.getUUID() + prefix);
            FileUploadUtil.inputStreamToFile(file.getInputStream(), file1);
            String name = (file.getOriginalFilename().split("\\."))[0] + ".html";
            upload = FileUploadUtil.upload(file1, SealConstant.DOC, name, UUIDUtil.getUUID());
            file1.delete();
        } catch (Exception e) {
            log.error("上传文件发生异常", e);
        }
        templateExt.setUrlId(upload);
        try {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotEmpty(fileName)) {
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                templateExt.setExtName(suffix);
            }
            templateExt.setTemplateData(file.getBytes());
            templateExt.setCreateTime(new Date());
            templateExt.setUpdateTime(new Date());
            templateExtMapper.insertFile(templateExt);
            return templateExt.getId();
        } catch (IOException e) {
            log.error("上传模板文件发生异常", e);
        }
        return null;
    }

    /**
     * 获取模板编号前缀
     *
     * @param templateRo
     * @param request
     * @return
     */
    public String getTemplateNoPrefix(com.credithc.signature.common.ro.manager.TemplateRo templateRo, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(templateRo.getChannelNo())) {
            buildCreatorInfo(templateRo, request);
        }
        Channel channel = channelService.selectChannelByCode(templateRo.getChannelNo());
        log.info("查询channel信息:channelObject=" + JSONObject.toJSONString(channel));
        return GeneralUtil.buildTemplateNoPrefix(channel.getChannelAlias());
    }

    /**
     * 新增模板
     *
     * @param templateRo
     * @param request
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void saveTemplateExt(com.credithc.signature.common.ro.manager.TemplateRo templateRo, HttpServletRequest request) throws Exception {
        Template template = new Template();
        //1.设置createId、createName
        buildCreatorInfo(templateRo, request);
        Channel channel = channelService.selectChannelByCode(templateRo.getChannelNo());
        BeanUtils.copyProperties(templateRo, template);
        //2.封装模板扩展表关联信息
        buildRefId(templateRo, template);
        templateRo.setRefId(template.getRefId() + "");
        //3.保存模板信息
        bulidTemplateInfo(template, channel);
        //4.保存审批流信息
        templateRo.setId(template.getId());
        templateRo.setTemplateNo(template.getTemplateNo());
        templateRo.setVersion(template.getVersion());
        Integer approvalId = null;
        approvalId = getApprovalId(templateRo);
        if (approvalId != null) {
            template.setApprovalId(approvalId);
        }
        templateMapper.updateByPrimaryKey(template);
        //5.处理公章规则号
        if (!ManagerConstant.PERSONAL.equals(templateRo.getSealType())) {
            insertOfficialSeal(templateRo.getOfficialSealId(), template.getTemplateNo());
        }
        log.info("新增模板：,templateNo = " + template.getTemplateNo() + ",templateName = " + template.getTemplateName() + ",templateInfo = " + JSONObject.toJSONString(template));
    }

    /**
     * 封装创建者信息
     *
     * @param templateRo
     * @param request
     * @throws Exception
     */
    private void buildCreatorInfo(com.credithc.signature.common.ro.manager.TemplateRo templateRo, HttpServletRequest request) throws Exception {
        Message<TokenRo> userByToken = authClient.getUserInfoByToken(request.getHeader("token"));
        log.info("数据权限查询结果:" + userByToken.toString());
        if (CoreCodes.CORE_SUCCESS == userByToken.getCode()) {
            TokenRo authData = userByToken.getData();
            String ehrId = authData.getEhrId();
            String userName = authData.getUserName();
            templateRo.setCreateId(ehrId);
            templateRo.setCreateName(userName);
            if (StringUtils.isEmpty(authData.getProductCode())) {
                throw new Exception("该租户下无此产品");
            } else {
                templateRo.setChannelNo(authData.getProductCode());
            }
        }
    }

    /**
     * 更新模板
     *
     * @param templateRo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public String updateTemplateExt(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {
        Template template = new Template();
        BeanUtils.copyProperties(templateRo, template);
        template.setUpdateTime(new Date());

        if (templateRo.getApproverIds() != null && templateRo.getApproverIds().size() > 0) {
            buildRefId(templateRo, template);
            //1校验 ，存在待审批、审批中的模板，不准许再次修改模板
            Template checkTemplate = null;
            try {
                checkTemplate = checkUpdateTemplate(templateRo);
            } catch (Exception e) {
                return e.getMessage();
            }
            //2 新增一条数据
            checkTemplate = newTemplate(checkTemplate);

            //模板内容不为空，则更新到历史表
            if (ManagerConstant.UPLOAD.equals(templateRo.getResource()) && StringUtils.isNotEmpty(templateRo.getRefId())) {
                template.setRefId(Integer.valueOf(templateRo.getRefId()));
                updateTemplateHistory(template);
                template.setVersion(GeneralUtil.buildVersion(templateRo));
                template.setTemplateStatus(ManagerConstant.DISABLE);
                template.setAuditStatus(ManagerConstant.UNAUDITED);
            } else {
                if (StringUtils.isNotEmpty(templateRo.getFileData())) {
                    insertFileData(templateRo, template);
                    updateTemplateHistory(template);
                    template.setVersion(GeneralUtil.buildVersion(templateRo));
                    template.setTemplateStatus(ManagerConstant.DISABLE);
                    template.setAuditStatus(ManagerConstant.UNAUDITED);
                }
            }

            //新增审批流
            Channel channel = channelMapper.selectByPrimaryKey(checkTemplate.getChannelId());
            templateRo.setChannelNo(channel.getChannelNo());
            templateRo.setId(checkTemplate.getId());
            if (StringUtils.isNotBlank(templateRo.getRefId())) {
                templateRo.setApprovalId(null);
                Integer approvalId = null;

                approvalId = getApprovalId(templateRo);

                if (approvalId != null) {
                    checkTemplate.setApprovalId(approvalId);
                }
            }

            checkTemplate.setVersion(template.getVersion());
            checkTemplate.setRefId(Integer.valueOf(templateRo.getRefId()));
            checkTemplate.setUpdateTime(new Date());
            templateMapper.updateByPrimaryKeySelective(checkTemplate);

        } else {
            BeanUtils.copyProperties(templateRo, template);
            templateMapper.updateByPrimaryKeySelective(template);
        }
        //处理公章规则号
        if (!ManagerConstant.PERSONAL.equals(templateRo.getSealType())) {
            updateOfficialSeal(templateRo.getOfficialSealId(), template.getTemplateNo());
        }
        log.info("修改模板：,templateNo = " + template.getTemplateNo() + ",templateName = " + template.getTemplateName() + ",templateInfo = " + JSONObject.toJSONString(template));
        return null;
    }

    private Template newTemplate(Template checkTemplate) {
        checkTemplate.setId(null);
        checkTemplate.setAuditStatus(ManagerConstant.UNAUDITED);
        checkTemplate.setTemplateStatus(ManagerConstant.DISABLE);
        checkTemplate.setUpdateTime(new Date());
        checkTemplate.setApprovalId(0);
        templateMapper.insert(checkTemplate);
        return checkTemplate;
    }

    private Template checkUpdateTemplate(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {
        Template template = templateMapper.selectByPrimaryKey(templateRo.getId());

        if (template == null) {
            throw new RuntimeException("模板不存在");
        }
        if (!template.getAuditStatus().equals(ManagerConstant.AUDITPASS) && !template.getAuditStatus().equals(ManagerConstant.AUDITREJECT)) {
            throw new RuntimeException("存在修改中模板，请审批完成后修改");
        }
        template.setResource(templateRo.getResource());
        template.setOperatorId(templateRo.getOperatorId());
        template.setOperatorName(templateRo.getOperatorName());
        if (StringUtils.isNotBlank(templateRo.getTemplateName())) {
            template.setTemplateName(templateRo.getTemplateName());
        }
        if (templateRo.getSealType() != null) {
            template.setSealType(templateRo.getSealType());
        }
        if (StringUtils.isNotBlank(templateRo.getRemark())) {
            template.setRemark(templateRo.getRemark());
        }
        Example example = new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("templateNo", template.getTemplateNo());
        List<Template> templates = templateMapper.selectByExample(example);

        if (templates.size() > 1) {
            throw new RuntimeException("存在修改中模板，请审批完成后修改");
        }
        return template;
    }


    private Integer getApprovalId(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {
        //获取对应的渠道信息
        ApprovalRo ar = new ApprovalRo();
        String token = bulidApprovalParams(templateRo, ar);
        Message message = approvalClient.submitApproval(ar, token);

        if (message.getCode() == 0) {
            return (Integer) message.getData();
        }
        log.error("保存审批流失败---------*%￥#------------" + message.getMsg());
        throw new RuntimeException("保存审批流失败:" + message.getMsg());
    }

    private String bulidApprovalParams(com.credithc.signature.common.ro.manager.TemplateRo templateRo, ApprovalRo ar) {
        String token;
        CompanyProductVo productMap = companyService.getProductMap(null, null, null);
        Map<String, ProductRo> proMap = productMap.getProMap();
        ProductRo productRo = proMap.get(templateRo.getChannelNo());
        ar.setUserInfoRos(templateRo.getUserInfoRos());
        ar.setApproverIds(templateRo.getApproverIds());
        ar.setCallerId(templateRo.getId() + "");
        ar.setDescription(StringUtils.isNotBlank(templateRo.getRemark()) ? templateRo.getRemark() : "");
        if (productRo != null) {
            ar.setCompanyId(productRo.getCompanyId());
            ar.setProductId(productRo.getProductId());
        }
        ar.setApplyData(bulidApplyData(templateRo));
        Template template = templateMapper.selectByPrimaryKey(templateRo.getId());
        templateRo.setApprovalId(template.getApprovalId());
        TemplateExt templateExt = null;
        if (StringUtils.isNotBlank(templateRo.getRefId())) {
            templateExt = templateExtMapper.selectByPrimaryKey(templateRo.getRefId());
        } else {
            templateExt = templateExtMapper.selectByPrimaryKey(template.getRefId());
        }
        ar.setEnclosureId(templateExt.getUrlId());
        ar.setEnclosureName(templateRo.getTemplateName());
        //获取token
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        token = request.getHeader("token");
        return token;
    }

    private String bulidApplyData(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {
        List<BasicNameValuePair> bp = new ArrayList<>();
        bp.add(new BasicNameValuePair("模板编号", templateRo.getTemplateNo()));
        bp.add(new BasicNameValuePair("签章类型", dictionaryService.selectOneByTypeAndCode(ManagerConstant.SEAL_TYPE, templateRo.getSealType() + "")));
        bp.add(new BasicNameValuePair("版本", templateRo.getVersion()));
        return JSON.toJSONString(bp);
    }

    private void buildRefId(com.credithc.signature.common.ro.manager.TemplateRo templateRo, Template template) {
        //文件上传
        if (ManagerConstant.UPLOAD.equals(templateRo.getResource()) && StringUtils.isNotEmpty(templateRo.getRefId())) {
            template.setRefId(Integer.valueOf(templateRo.getRefId()));
        } else if (ManagerConstant.ONLINE.equals(templateRo.getResource()) && StringUtils.isNotBlank(templateRo.getFileData())) {
            insertFileData(templateRo, template);
        }
    }

    private void insertFileData(com.credithc.signature.common.ro.manager.TemplateRo templateRo, Template template) {
        String fileData = templateRo.getFileData();
        String fileName = templateRo.getTemplateName() + ".html";
        // 获取文件后缀
        String upload = null;
        try {
            final File excelFile = File.createTempFile(UUIDUtil.getUUID(), "html");
            // MultipartFile to File
            FileOutputStream fos = new FileOutputStream(excelFile);
            fos.write(fileData.getBytes(), 0, fileData.getBytes().length);
            fos.flush();
            fos.close();
            upload = FileUploadUtil.upload(excelFile, SealConstant.DOC, fileName, UUIDUtil.getUUID());
            excelFile.delete();
        } catch (Exception e) {
            log.error("上传文件失败" + e.getMessage());
        }

        TemplateExt templateExt = new TemplateExt();
        templateExt.setExtName(ManagerConstant.FTL);
        templateExt.setUrlId(upload);
        templateExt.setTemplateData(fileData.getBytes());
        templateExt.setCreateTime(new Date());
        templateExt.setUpdateTime(new Date());
        templateExtMapper.insertFile(templateExt);
        Integer id = templateExt.getId();
        template.setRefId(id);
        templateRo.setRefId(id + "");
    }


    public Message approvalUpdate(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {

        Template template = templateMapper.selectByPrimaryKey(templateRo.getId());
        Channel channel = channelMapper.selectByPrimaryKey(template.getChannelId());
        templateRo.setChannelNo(channel.getChannelNo());
        //更新审批流
        try {
            ApprovalRo ar = new ApprovalRo();
            String token = bulidApprovalParams(templateRo, ar);
            if (templateRo.getApprovalId() != null) {
                ar.setId(templateRo.getApprovalId());
                Message message = approvalClient.updateApprovers(ar, token);
                template.setRemark(templateRo.getRemark());
                template.setTemplateStatus(ManagerConstant.DISABLE);
                template.setAuditStatus(ManagerConstant.UNAUDITED);
                templateMapper.updateByPrimaryKeySelective(template);
                log.info(message.getMsg());
                if (message.getCode() != 0) {
                    return message;
                }
            } else {
                Integer approvalId = null;
                try {
                    approvalId = getApprovalId(templateRo);
                } catch (Exception e) {
                    return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, e.getMessage());
                }
                templateRo.setApprovalId(approvalId);
            }
        } catch (Exception e) {
            log.error("更新审批流失败", e);
        }
        return null;
    }

    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public String saveTemplateExt1(com.credithc.signature.common.ro.manager.TemplateRo templateRo) {
        Template template = new Template();
        String createId = "";
        String createName = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Message token = authClient.getUserByToken(request.getHeader("token"));
        Map map = (Map) token.getData();
        if (map != null) {
            if (StringUtils.isBlank(templateRo.getChannelNo())) {
                log.info("获取用户信息返回结果：" + map.toString());
                templateRo.setChannelNo((String) map.get(ManagerConstant.PRODUCTCODE));

            }
            createId = (String) map.get(ManagerConstant.EHRID);
            createName = (String) map.get(ManagerConstant.USERNAME);
            templateRo.setCreateId(createId);
            templateRo.setCreateName(createName);
        }
        log.info("#####$$$$## createId:{}   createName:{}", createId, createName);
        templateRo.setPageNo(1);
        templateRo.setPageSize(1);
        String channelNo = templateRo.getChannelNo();
        if (StringUtils.isBlank(channelNo)) {
            return "该租户下无此产品";
        }
        Channel channel = channelService.selectChannelByCode(channelNo);
        BeanUtils.copyProperties(templateRo, template);
        buildRefId(templateRo, template);
        templateRo.setRefId(template.getRefId() + "");
        bulidTemplateInfo(template, channel);

        templateRo.setId(template.getId());
        templateRo.setTemplateNo(template.getTemplateNo());
        templateRo.setVersion(template.getVersion());
        Integer approvalId = null;
        try {
            approvalId = getApprovalId(templateRo);
        } catch (Exception e) {

            throw new RuntimeException(e.getMessage());

        }
        if (approvalId != null) {
            template.setApprovalId(approvalId);
        }
        templateMapper.updateByPrimaryKey(template);
        //处理公章规则号
        if (!ManagerConstant.PERSONAL.equals(templateRo.getSealType())) {
            insertOfficialSeal(templateRo.getOfficialSealId(), template.getTemplateNo());
        }
        log.info("新增模板：,templateNo = " + template.getTemplateNo() + ",templateName = " + template.getTemplateName() + ",templateInfo = " + JSONObject.toJSONString(template));
        return null;
    }

    /**
     * 封装模板编号
     *
     * @param template
     * @param channel
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public synchronized void bulidTemplateInfo(Template template, Channel channel) {
        template.setChannelId(channel.getId());
        template.setVersion(ManagerConstant.INITVERSION);
        template.setAuditStatus(ManagerConstant.UNAUDITED);
        template.setTemplateStatus(ManagerConstant.DISABLE);
        template.setCreateTime(new Date());
        template.setUpdateTime(new Date());
        template.setVip(0);
        log.info("保存模板信息template=" + template.toString());
        templateMapper.insert(template);
    }


}
